package com.wd.util;

import org.apache.log4j.helpers.LogLog;

/**
 * 监视运行时间,
 * 
 * @author long
 * 
 */
public class TimeWatch {
	private final String operateMsg;
	private long first = 0L;
	private long second = 0L;
	private long spendTime = 0L;
	public boolean isTimerFormat = false;
	public static final int DAYMILLI = 24 * 60 * 60 * 1000;
	public static final int HOURMILLI = 60 * 60 * 1000;
	public static final int MINUTEMILLI = 60 * 1000;

	public TimeWatch(String _operateMsg) {
		operateMsg = _operateMsg;
		start();
	}

	public void start() {
		this.first =System.currentTimeMillis();
	}

	/**
	 * 打印运行结果
	 * 
	 * @param isError
	 *            是否输出error日志
	 * @param _spendTime
	 *            超出时间
	 */
	public void stop(boolean isError, long _spendTime) {
		this.setSecond(System.currentTimeMillis());
		setSpendTime(this.getSecond() - this.first);
		if (isError && getSpendTime() > _spendTime) {
			LogLog.error(String.format("[%s]执行总时间 :%s毫秒", new Object[] { operateMsg, isTimerFormat ? getTime(this.spendTime) : this.spendTime }));
		}
	}
	public void stop(String msg, long _spendTime) {
		this.setSecond(System.currentTimeMillis());
		setSpendTime(this.getSecond() - this.first);
		if (getSpendTime() > _spendTime) {
			LogLog.error(String.format("[%s][%s]执行总时间 :%s毫秒", new Object[] { operateMsg,msg, isTimerFormat ? getTime(this.spendTime) : this.spendTime }));
		}
	}
	public void stop(String msg) {
		this.setSecond(System.currentTimeMillis());
		setSpendTime(this.getSecond() - this.first);
//		Log.info(String.format("[%s][%s]执行总时间 :%s毫秒,开始时间:%s结束时间:%s", new Object[] { operateMsg, msg, this.spendTime, DateUtil.format(new Date(this.first)), DateUtil.format(new Date(this.second)) }));
		LogLog.debug(String.format("[%s][%s]执行总时间 :%s毫秒", new Object[] { operateMsg, msg, this.spendTime }));
	}

	public static String getTime(long _spendTime) {
		int day = (int) _spendTime / DAYMILLI;
		long milisecond = _spendTime % DAYMILLI;
		int hour = (int) milisecond / HOURMILLI;
		milisecond = milisecond % HOURMILLI;
		int minute = (int) milisecond / MINUTEMILLI;
		milisecond = milisecond % MINUTEMILLI;
		int second = (int) milisecond / 1000;
		milisecond = milisecond % 1000;
		return String.format("%s天%s时%s分%s秒%s", day, hour, minute, second, milisecond);
	}

	/**
	 * 重置计时器
	 */
	public void reset() {
		this.first = 0;
		this.setSecond(0);
	}

	public long getSecond() {
		return second;
	}

	public void setSecond(long second) {
		this.second = second;
	}

	public long getSpendTime() {
		return spendTime;
	}

	public void setSpendTime(long spendTime) {
		this.spendTime = spendTime;
	}
}
